package easyjava.hibernate.dao;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.query.Query;

import easyjava.hibernate.bean.Student;

public class StudentDao {

	private Session session;

	public StudentDao(Session session) {
		this.session = session;
	}

	public List<Student> list() {
		Query<Student> query = session.createQuery("from Student", Student.class);

		return query.getResultList();
	}

	public List<Student> listByName(String name) {
		Query<Student> query = session.createQuery("from Student where firstname like :name or lastname like:name",
				Student.class);
		query.setParameter("name", "%" + name + "%");

		return query.getResultList();
	}

	public Student getStudentById(int id) {
		return session.get(Student.class, id);
	}
	public List listMsg(){
		Query query =session.createQuery("select s.sid,s.firstname,s.lastname,ap.building,ap.floor,ap.room,ap.bed "
				+ "from Student s,Apartment ap,Accommodation ac "
				+ "where ac.apartmnetId=ap.id and s.accomodationId=ac.id");
		
		return query.getResultList();
	}

	public void insert(Student student) {
		Transaction tx = session.beginTransaction();
		try {

			session.save(student);
			tx.commit();
		} catch (HibernateException e) {
			e.printStackTrace();
			tx.rollback();
		}
	}
	public void update(Student student){
		Transaction tx = session.beginTransaction();
		try {

			session.update(student);
			tx.commit();
		} catch (HibernateException e) {
			e.printStackTrace();
			tx.rollback();
		}
		
	}
	public void delete(Student student){
		Transaction tx = session.beginTransaction();
		try {
			
			session.delete(student);
			tx.commit();
		} catch (HibernateException e) {
			e.printStackTrace();
			tx.rollback();
		}
		
	}

}
